<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>天气查询</title>
  <style>
    #app {
      text-align: center;
    }

    .weatherList {
      width: 240px;
      margin: 20px auto;
      text-align: left;
    }

    .tipsInfo {
      color: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <h3>天气查查查</h3>
    <input type="text" placeholder="请输入查询的城市" v-model.lazy.trim="city" @keyup.enter="searchWeather" />
    <button @click="searchWeather">点击查询</button>
    <h3 v-show="weatherList.length<=0" class="tipsInfo">{{tipsInfo}}</h3>
    <div class="weatherList" v-show="weatherList.length>0">
      <h3 v-show="cityName"><span style="color:blue;">{{cityName}}</span>近几日天气情况</h3>
      <p v-for="(item,index) in weatherList" :key="index">
        {{item.type}}{{item.data}} {{item.high}} {{item.low}}
        <span v-if="item.type.indexOf('雨')>-1">🌧️</span>
        <span v-if="item.type.indexOf('阴')>-1 || item.type.indexOf('云')>-1">🌥️</span>
        <span v-if="item.type.indexOf('晴')>-1">🌞</span>
        <span v-if="item.type.indexOf('霾')>-1">🌁</span>
        <span v-if="item.type.indexOf('雪')>-1">❄️</span>
      </p>
    </div>
  </div>
</body>

</html>
<!-- 导入vue.js的包 -->
<script src="./js/vue.js"></script>
<script src="./js/jquery-1.12.4.min.js"></script>
<script>
  const app = new Vue({
    el: "#app",
    data: {
      // city用来保存用户输入的城市，使用v-model进行双向绑定
      // cityName保存用户输入的城市名称，并将其渲染到h3中，当ajax发送成功后会将输入框清空
      // tipsInfo用来存储错误信息
      // weatherList用来保存用户输入的
      city: "",
      cityName: "",
      tipsInfo: "",
      weatherList: []
    },
    methods: {
      // searchWeather ，当用户在输入框后按下enter键或者点价button按钮都会触发这个事件
      searchWeather() {
        // 如果输入的城市为空，则直接退出，并提示用户不能输入空内容
        if (!this.city) {
          alert('请输入不为空的城市');
          return;
        }
        else {
          $.ajax({
            type: "GET",
            url: `http://wthrcdn.etouch.cn/weather_mini?city=${this.city}`,
            success: res => {
              // 将刚才输入的城市信息保留
              this.cityName = this.city;
              const jsonData = JSON.parse(res);
              //  OK的话代表获取到了数据
              if (jsonData.desc === 'OK') {
                this.weatherList = jsonData.data.forecast;
                console.log(jsonData.data);
                this.city = "";
              }
              else {
                console.log("城市输入错误,请检查输入的城市名字");
                this.weatherList = [];
                this.cityName = "";
                this.tipsInfo = "城市名称不符 请重新输入";
                this.city = "";
              }
            },
            error(err) {
              console.log(err);

            }

          })
        }
      }
    },
    emptyInfo() {
      this.tipsInfo = ""
    }


  })
</script>